package com.git.contractmanagement.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

public class VerifyUtil {

    /**
     * 校验手机号格式
     * @param phone
     * @return
     */
    public static boolean verifyFormatPhone(String phone) {
        if (phone == null) {
            return false;
        }
        // 中国手机号正则：1开头，第二位是3-9，后面9位数字
        String regex = "^1[3-9]\\d{9}$";
        return Pattern.matches(regex, phone);

    }

    /**
     * 检验身份证号码格式
     * @param idCard
     * @return
     */
    public static boolean isValidIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return false;
        }
        if (!idCard.matches("\\d{17}[\\dXx]")) {
            return false;
        }
        // 校验出生日期格式
        try {
            LocalDate.parse(idCard.substring(6, 14), DateTimeFormatter.BASIC_ISO_DATE);
        } catch (Exception e) {
            return false;
        }
        // 校验校验码
        char expected = calculateCheckCode(idCard.substring(0, 17));
        char actual = idCard.charAt(17);
        return (actual == expected) || (actual == 'X' && expected == 'x') || (actual == 'x' && expected == 'x');
    }

    private static char calculateCheckCode(String id17) {
        int[] w = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
        char[] c = {'1','0','X','9','8','7','6','5','4','3','2'};
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += Character.getNumericValue(id17.charAt(i)) * w[i];
        }
        return c[sum % 11];
    }
}
